<?php
namespace app\service;

use AlibabaCloud\SDK\Sts\V20150401\Models\AssumeRoleResponseBody\credentials;
use AlibabaCloud\SDK\Sts\V20150401\Sts;
use \Exception;
use AlibabaCloud\Tea\Exception\TeaError;
use AlibabaCloud\Tea\Utils\Utils;

use Darabonba\OpenApi\Models\Config;
use AlibabaCloud\SDK\Sts\V20150401\Models\AssumeRoleRequest;
use AlibabaCloud\Tea\Utils\Utils\RuntimeOptions;
use think\initializer\Error;
use think\response\Json;

class AliyunOss {

    /**
     * 使用AK&SK初始化账号Client
     * @param string $accessKeyId
     * @param string $accessKeySecret
     * @return Sts Client
     */
    public static function createClient(string $accessKeyId, string $accessKeySecret): Sts
    {
        $config = new Config([
            // 您的 AccessKey ID
            "accessKeyId" => $accessKeyId,
            // 您的 AccessKey Secret
            "accessKeySecret" => $accessKeySecret
        ]);
        // 访问的域名
        $config->endpoint = "sts.cn-hangzhou.aliyuncs.com";
        return new Sts($config);
    }


    /**
     * @param int $expirationTime
     * @param string $roleName
     * @param string $roleArn
     * @return credentials|mixed
     */
    public static function main(int $expirationTime = 1200, string $roleName = "oss", string $roleArn = "acs:ram::1930244753635285:role/oss")
    {
        $client = self::createClient(env('COSSTS.OssAccessKeyID', ''), env('COSSTS.OssAccessKeySecret', ''));
        $assumeRoleRequest = new AssumeRoleRequest([
            "durationSeconds"   => $expirationTime,
            "roleSessionName"   => $roleName,
            "roleArn"           => $roleArn,
        ]);
        $runtime = new RuntimeOptions([]);
        try {
            // 复制代码运行请自行打印 API 的返回值
            return $client->assumeRoleWithOptions($assumeRoleRequest, $runtime)->body->credentials;
        } catch (Exception $error) {
            // 日志
            trace(json_encode($error->getErrorInfo()['data']), "error");
            // 返回
            return $error->getErrorInfo()['data']['Message'];
        }
    }
}
